﻿using System.Drawing;
using System.Drawing.Drawing2D;

namespace MultiThumbnail
{
    static class GraphicsManager
    {
        /// <summary>
        /// Resizes the image.
        /// </summary>
        /// <param name="imgToResize">The img to resize.</param>
        /// <param name="size">The size that is required.</param>
        /// <returns></returns>
        public static Image ResizeImage(Image imgToResize, Size size)
        {
            return ResizeImage(imgToResize, size, false);
        }

        /// <summary>
        /// Resizes the image.
        /// </summary>
        /// <param name="imgToResize">The img to resize.</param>
        /// <param name="size">The size that is required.</param>
        /// <param name="onlyByWidth">Resize picture to size with specified width and ignored height.</param>
        /// <returns></returns>
        public static Image ResizeImage(Image imgToResize, Size size, bool onlyByWidth)
        {
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercentW = (size.Width / (float)sourceWidth);
            float nPercentH = (size.Height / (float)sourceHeight);
            float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;
            if (onlyByWidth)
                nPercent = nPercentW;

            var destWidth = (int)(sourceWidth * nPercent);
            var destHeight = (int)(sourceHeight * nPercent);
            var b = new Bitmap(destWidth, destHeight);
            using (var g = Graphics.FromImage(b))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            }

            return b;
        }
    }
}
